# -*- coding=utf-8 -*-
# 2021.
# @zlk 
# zhanglk960127@163.com]
# 从blast结果里找到符合标准的假基因
import sys
import os
import re

file2=open(sys.argv[2],'r') # blast_file
file3=open(sys.argv[3],'w')
def merge_list_func(loop_list):
    sort_loop_list=sorted(loop_list,key=lambda x:x[0])
    out_list=[]
    start_list=sort_loop_list[0]
    for pos_list in sort_loop_list[1:]:
        if pos_list[0]>start_list[1]:
            out_list.append(start_list)
            start_list=pos_list
        elif pos_list[0]<start_list[1]:
            if pos_list[1]<=start_list[1]:
                continue
            else:
                start_list=[start_list[0],pos_list[1]]
    out_list.append(start_list)
    return out_list

total_gene_length_dict={}
for msyn in os.listdir(sys.argv[1]):
    if msyn.startswith('mSynF'):
        loop_pos_file=open(sys.argv[1]+'/'+msyn+'/species.gff_pos')
        for line in loop_pos_file:
            line_list=line.strip().split('\t')
            total_gene_length_dict[line_list[0]]=int(line_list[2])
        loop_pos_file.close()
        
blast_dict={}    
for line in file2:
    line_list=line.strip().split('\t')
    # num=re.findall('\d+',line_list[0])[-1]
    # gene_id=line_list[0][:-(len(num)+1)]
    gene_id=line_list[0]
    if int(line_list[3])<40 and float(line_list[2])<60:
        continue
    if gene_id not in blast_dict.keys():
        blast_dict[gene_id]={}
    if line_list[1] not in blast_dict[gene_id].keys():
        blast_dict[gene_id][line_list[1]]=[[],[]]
    if int(line_list[6])<int(line_list[7]):
        add_list1=[int(line_list[6]),int(line_list[7])]
    else:
        add_list1=[int(line_list[7]),int(line_list[6])]
    if int(line_list[8])<int(line_list[9]):
        add_list2=[int(line_list[8]),int(line_list[9])]
    else:
        add_list2=[int(line_list[9]),int(line_list[8])]
    blast_dict[gene_id][line_list[1]][0].append(add_list1)
    blast_dict[gene_id][line_list[1]][1].append(add_list2)

for key,value in blast_dict.items():
    big_length=0
    big_list=[]
    big_id=''
    gene_length=total_gene_length_dict[key]
    for key1,value1 in value.items():
        num=0
        length_list=merge_list_func(value1[0])
        length_list2=merge_list_func(value1[1])
        
        for i  in length_list:
            num+=(i[1]-i[0]+1)
        if num>big_length:
            big_length=num
            big_id=key1
            big_list=[length_list2[0][0],length_list2[-1][1]]
    if big_length/gene_length>0.5:
        file3.write(key+'\t'+str(big_length)+'\t'+big_id+'\t'+str(big_list[0])+'\t'+str(big_list[1])+'\n')
        
        
    
